package com.gitee.cashzhang27.test.boot.graphql.webflux.graphql.components;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gitee.cashzhang27.test.boot.graphql.webflux.graphql.JsonSerializer;
import java.io.IOException;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;

@Component
@AllArgsConstructor
public class JacksonJsonSerializer implements JsonSerializer {

  private final ObjectMapper objectMapper;

  @Override
  public String serialize(Object object) {
    try {
      return objectMapper.writeValueAsString(object);
    } catch (IOException e) {
      throw new RuntimeException("Error serializing object to JSON: " + e.getMessage(), e);
    }
  }

  @Override
  public <T> T deserialize(String json, Class<T> requiredType) {
    try {
      return objectMapper.readValue(json, requiredType);
    } catch (IOException e) {
      throw new RuntimeException("Error deserializing object from JSON: " + e.getMessage(), e);
    }
  }
}
